package com.yhh.zhongdian.help;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.util.Log;

import com.yhh.zhongdian.BuildConfig;
import com.yhh.zhongdian.MyApplication;
import com.yhh.zhongdian.R;
import com.yhh.zhongdian.base.MBaseActivity;
import com.yhh.zhongdian.base.observer.MyObserver;
import com.yhh.zhongdian.help.permission.Permissions;
import com.yhh.zhongdian.help.permission.PermissionsCompat;
import com.yhh.zhongdian.utils.GsonUtils;
import com.yhh.zhongdian.utils.VersionUtil;
import com.yhh.zhongdian.view.activity.AboutActivity;
import com.yhh.zhongdian.view.activity.MainActivity;
import com.yhh.zhongdian.widget.modialog.ApkDownDialog;

import java.io.File;

import androidx.core.content.FileProvider;

/**
 * 版本校验工具
 * Created by user on 20/3/12.
 */

public class VersionCheckHelper {
    private static final String versionInfo = "update_version_info";

    public static void needUpdate(MBaseActivity activity) {
        String s = MyApplication.getConfigPreferences().getString(versionInfo, "");
        if (s.isEmpty()) {
            checkForUpdate(activity);
            return;
        }

        VersionUtil.CheckVersionBo versionSnapshot = GsonUtils.parseJObject(s, VersionUtil.CheckVersionBo.class);
        Log.d(activity.TAG, versionSnapshot.toString());
        if (MyApplication.getVersionCode() < versionSnapshot.code) {
            showSimpleDialog(activity, versionSnapshot);
            // 弹窗下载进度方式，因为无法下载完整的apk，暂时先放弃
//            File apk = getDownloadApk(activity, versionSnapshot.code);
//            if (apk != null) {
//                // 已经下载了，则直接进入安装
//                installApp(activity, apk);
//
//            } else {
//                // 没有下载好，则弹出下载更新弹窗
//                showUpdateDialog(activity, versionSnapshot);
//            }
        } else {
            // 版本号一样，判断是否需要请求一下，有没有最新的版本
            long now = System.currentTimeMillis();
            if (now - versionSnapshot.time >= 86400_000L) {
                checkForUpdate(activity);
            } else {
                // 不需要更新
                versionSnapshot.setTime(now);
                saveVersionInfo(versionSnapshot);
                if (!(activity instanceof MainActivity)) {
                    activity.toast("当前已经是最新版本了哦");
                }
            }
        }
    }

    private static void checkForUpdate(MBaseActivity activity) {
        VersionUtil.checkForUpdate(activity.getString(R.string.check_version_url))
                .subscribe(new MyObserver<VersionUtil.CheckVersionBo>() {
                    @Override
                    public void onNext(VersionUtil.CheckVersionBo checkVersionBo) {
                        if (checkVersionBo.downUrl == null) {
                            return;
                        }

                        saveVersionInfo(checkVersionBo);
                        if (checkVersionBo.update) {
//                    showUpdateDialog(activity, checkVersionBo);
                            Log.d(activity.TAG, "show simpleDialog: " + checkVersionBo);
                            showSimpleDialog(activity, checkVersionBo);
                        } else if (activity instanceof AboutActivity) {
                            Log.d(activity.TAG, "show simpleToast: " + checkVersionBo);
                            activity.toast("当前已经是最新版本了哦");
                        }
                    }
                });
    }

    /**
     * 直接跳转到下载页面
     *
     * @param activity
     * @param intentName
     * @param address
     */
    private static void openIntent(MBaseActivity activity, String intentName, String address) {
        try {
            Intent intent = new Intent(intentName);
            intent.setData(Uri.parse(address));
            activity.startActivity(intent);
        } catch (Exception e) {
            activity.toast(R.string.can_not_open, -1);
        }
    }

    private static void saveVersionInfo(VersionUtil.CheckVersionBo bo) {
        MyApplication.getConfigPreferences().edit().putString(versionInfo, GsonUtils.toJsonWithSerializeNulls(bo)).apply();
    }

    private static void showSimpleDialog(MBaseActivity activity, VersionUtil.CheckVersionBo bo) {
        ApkDownDialog apkDownDialog = ApkDownDialog.builder(activity);
        apkDownDialog.setClick(bo.getContent(), bo.getDownUrl(), url -> openIntent(activity, Intent.ACTION_VIEW, url)).show();
    }

    private static void showUpdateDialog(MBaseActivity activity, VersionUtil.CheckVersionBo bo) {
        ApkDownDialog apkDownDialog = ApkDownDialog.builder(activity);
        apkDownDialog.setCallback(bo.getContent(), bo.getDownUrl(), getDownloadPath(activity), getApkName(bo.getCode()),
                new ApkDownDialog.Callback() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        apkDownDialog.dismiss();
                        installApp(activity, file);
                    }

                    @Override
                    public void onDownloading(int progress) {
                        apkDownDialog.updateProgress(progress);
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        apkDownDialog.dismiss();
                        e.printStackTrace();
                    }
                });
        if (!activity.isFinishing()) {
            apkDownDialog.show();
        }
    }

    private static void installApp(Activity activity, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean b = activity.getPackageManager().canRequestPackageInstalls();
            if (!b) {
                // 无权限，则申请权限
                Looper.prepare();
                new PermissionsCompat.Builder(activity)
                        .addPermissions(Permissions.REQUEST_INSTALL_PACKAGES)
                        .rationale(R.string.update_version_per)
                        .request();
                Looper.loop();
                return;
            }
        }

        // 启动安装
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri contentUri = FileProvider.getUriForFile(activity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", file);
        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        activity.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    private static File getDownloadApk(MBaseActivity activity, int code) {
        String path = getDownloadPath(activity);
        String name = getApkName(code);

        File file = new File(path + "/" + name);
        if (file.exists()) {
            return file;
        }

        return null;
    }

    private static String getDownloadPath(MBaseActivity activity) {
        String path = activity.getCacheDir().getAbsolutePath();
        return FileHelp.getCachePath();
    }

    private static String getApkName(int code) {
        return "ZhongDian-" + code + ".apk";
    }
}
